import 'package:get/get.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import '../../models/product.dart';
import '../../services/auth_service.dart';
import '../../services/product_service.dart';

class ShopLogic extends GetxController {
  final AuthService _authService = AuthService();
  final ProductService _productService = ProductService();

  final RxList<Product> productList = <Product>[].obs;
  final isLoading = true.obs;
  final isAdmin = false.obs;

  @override
  void onInit() {
    super.onInit();
    _checkIfAdmin();
    loadProducts();
  }

  Future<void> _checkIfAdmin() async {
    isAdmin.value = await _authService.isCurrentUserAdmin();
  }

  Future<void> loadProducts() async {
    isLoading.value = true;
    try {
      final list = await _productService.getAllProducts();
      productList.value = list;
    } catch (e) {
      SmartDialog.showToast('加载商品失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  void goToAddProduct() {
    Get.toNamed('/add-product')?.then((_) => loadProducts());
  }

  void goToProductDetail(Product product) {
    Get.toNamed('/product-detail', arguments: product)?.then((result) {
      // 如果返回结果为true，表示需要刷新商品列表
      if (result == true) {
        loadProducts();
      }
    });
  }
}
